﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using KharaPos.Web.Entities;
using KharaPos.Web.Services;

namespace KharaPos.ViewModels
{
    public class CategoryManagementViewModel:INotifyPropertyChanged
    {
        private readonly CatalogContext _dataContext;
        private bool _IsLoading;
        private ObservableCollection<Category> _AvailableCategories;

        public CategoryManagementViewModel()
        {
            _dataContext = new CatalogContext();
            LoadCategories();
        }

        private void LoadCategories()
        {
            IsLoading = true;
            var loadOperation= _dataContext.Load(_dataContext.GetCategoriesQuery());
            loadOperation.Completed += FinishedLoading;
        }

        protected bool IsLoading
        {
            get { return _IsLoading; }
            set
            {
                _IsLoading = value;
                NotifyPropertyChanged("IsLoading");
            }
        }

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged!=null)
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }

        void FinishedLoading(object sender, EventArgs e)
        {
            IsLoading = false;
            AvailableCategories=
                new ObservableCollection<Category>(_dataContext.Categories);
        }

        public ObservableCollection<Category> AvailableCategories
        {
            get
            {
                return _AvailableCategories;
            }
            set
            {
                _AvailableCategories = value;
                NotifyPropertyChanged("AvailableCategories");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
